$(function() {

    $(".form-myt-purchase-purchase-return-order-bpmInput").data("formOptions", {
        updateTotalAmount : function() {
            var $form = $(this);
            var $grid = $form.find(".grid-myt-purchase-purchase-return-order-bpmInput");
            var userData = {
                "commodity.display" : "合计："
            };
            //更新表格汇总统计数据
            userData.quantity = $grid.jqGrid('sumColumn', 'quantity');
            userData.amount = $grid.jqGrid('sumColumn', 'amount');
            userData.deliveryAmount = $grid.jqGrid('sumColumn', 'deliveryAmount');
            userData.discountAmount = $grid.jqGrid('sumColumn', 'discountAmount');

            $grid.jqGrid("footerData", "set", userData, true);
            var totalAmount = userData.deliveryAmount + userData.amount;
            $form.find(".span-total-amount").html(totalAmount);
            $form.setFormDatas({
                amount : userData.amount,
                totalDiscountAmount : userData.discountAmount,
                totalDeliveryAmount : userData.deliveryAmount,
                totalAmount : totalAmount
            });

        },
        bindEvents : function() {
            var $form = $(this);
            var $grid = $form.find(".grid-myt-purchase-purchase-return-order-bpmInput");
           
            // 从销售单选取
            $form.find(".btn-select-purchase-receipt").click(function() {
                var $purchaseReceiptId = $form.find("input[name='purchaseReceipt.id']");
                var purchaseReceiptId = $purchaseReceiptId.val();
                if (purchaseReceiptId != '') {
                    if (confirm("一个采购退货单只允许从单个采购（收货）单选取，重新选取将清空当前相关数据以新选择采购（收货）单数据覆盖，确认继续？")) {
                        $grid.clearGridData();
                        $form.data("formOptions").updateTotalAmount.call($form);
                    }else{
                        return;
                    }
                }

                $(this).popupDialog({
                    url : WEB_ROOT + '/myt/purchase/purchase-receipt!forward?_to_=selection',
                    title : '选取采购（收货）单',
                    callback : function(data) {
                        var master = data.master;
                        var rows = data.rows;
                        $purchaseReceiptId.val(master.id);// 设置关联
                        // 设置供货商
                        $form.setFormDatas({
                             'supplier.id' : master['supplier.id']
                        }, true);
                        
                        $.each(rows, function(i, row) {
                            console.info(row);
                            
                            row['purchaseReceiptDetail.id'] = row['id'];// 设置关联
                            $grid.data("gridOptions").calcRowAmount.call($grid, row);// 计算
                            var newid = $grid.jqGrid('insertNewRowdata', row);// 插入行
                            
                            // 计算并设置行项号
                            var idx = $grid.find("tr[id='" + newid + "'] >td.jqgrid-rownum").html().trim();
                            $grid.jqGrid('setRowData', newid, {
                                subVoucher : 100 + idx * 10
                            });
                            
                            // 计算汇总数据
                            $form.data("formOptions").updateTotalAmount.call($form);
                        });
                    }
                })
            });
        }
    });

    $(".grid-myt-purchase-purchase-return-order-bpmInput").data("gridOptions", {
        calcRowAmount : function(rowdata, src) {

            rowdata['originalAmount'] = MathUtil.mul(rowdata['price'], rowdata['quantity']);
            //src=='deliveryAmount'的时候不计算折扣，避免已计算好的折扣再次计算出现精度问题
            if (src != 'deliveryAmount') {
                if (src == 'discountAmount') {
                    rowdata['discountRate'] = MathUtil.div(rowdata['discountAmount'], rowdata['originalAmount'], 5) * 100;
                    rowdata['amount'] = MathUtil.sub(rowdata['originalAmount'], rowdata['discountAmount']);
                } else if (src == 'amount') {
                    rowdata['discountAmount'] = MathUtil.sub(rowdata['originalAmount'], rowdata['amount']);
                    rowdata['discountRate'] = MathUtil.div(rowdata['discountAmount'], rowdata['originalAmount'], 5) * 100;
                } else {
                    rowdata['discountAmount'] = MathUtil.div(MathUtil.mul(rowdata['discountRate'], rowdata['originalAmount']), 100);
                    rowdata['amount'] = MathUtil.sub(rowdata['originalAmount'], rowdata['discountAmount']);
                }
            }
            rowdata['costAmount'] = MathUtil.add(rowdata['amount'], rowdata['deliveryAmount']);
            rowdata['costPrice'] = MathUtil.div(rowdata['costAmount'], rowdata['quantity'], 2);

        },
        updateRowAmount : function(src) {

            var $grid = $(this);
            var rowdata = $grid.jqGrid("getEditingRowdata");
            $grid.data("gridOptions").calcRowAmount.call($grid, rowdata, src);
            $grid.jqGrid("setEditingRowdata", rowdata);

        },
        batchEntitiesPrefix : "purchaseReturnOrderDetails",
        url : function() {
            var pk = $(this).attr("data-pk");
            if (pk) {
                return WEB_ROOT + "/myt/purchase/purchase-return-order!purchaseOrderDetails?id=" + pk + "&clone=" + $(this).attr("data-clone");
            }
        },
        colModel : [ {
            label : '所属单据主键',
            name : 'purchaseRetrunOrder.id',
            hidden : true,
            hidedlg : true,
            editable : true,
            formatter : function(cellValue, options, rowdata, action) {
                var pk = $(this).attr("data-pk");
                return pk ? pk : "";
            }
        }, {
            name : 'purchaseReceiptDetail.id',
            hidden : true,
            hidedlg : true,
            editable : true
        },  {
            label : '商品主键',
            name : 'commodity.id',
            hidden : true,
            hidedlg : true,
            editable : true
        }, {
            name : 'commodity.sku',
            hidden : true,
            hidedlg : true,
            editable : true
        }, {
            label : '行项号',
            name : 'subVoucher',
            width : 50,
            editable : true,
            editrules : {
                required : true
            },
            editoptions : {
                dataInit : function(elem) {
                    var $el = $(elem);
                    if ($el.val() == '') {
                        var $jqgrow = $el.closest(".jqgrow");
                        var idx = $jqgrow.parent().find(".jqgrow:visible").index($jqgrow);
                        $el.val(100 + idx * 10);
                    }
                }
            },
            align : 'center'
        }, {
            label : '退货商品',
            name : 'commodity.display',
            editable : true,
            width : 200,
            editrules : {
                required : true
            },
            editoptions : {
                placeholder : '输入商品信息提示选取或双击选取',
                dataInit : function(elem) {
                    var $grid = $(this);
                    var $elem = $(elem);
                    // 弹出框的选取回调函数
                    var selectCommodity = function(item) {
                        
                        var ids = $grid.jqGrid('getDataIDs');// 返回当前grid里所有数据的id
                        
                        var existRowId = null;// 如果是已经选择过的商品，那么这是哪个商品的所在行行号
                        var oldQuantity = null;// 如果是已经选择过的商品，那么这是哪个商品的数量
                        for(i=0; i<ids.length; i++){
                            var row = $grid.jqGrid('getRowData', ids[i]);//获取单行数据根据ID
                            if(item['sku'] == row['commodity.sku']){
                                // SKU一致即认为是同一商品
                                existRowId = ids[i];
                                oldQuantity = row.quantity;
                                break;
                            }
                        }
                        
                        if(existRowId){
                            $grid.jqGrid("setRowData", existRowId, {
                                'quantity' : Number(oldQuantity)+1
                            });
                            var myrowdata = $grid.jqGrid('getRowData', existRowId);//获取单行数据根据ID
                            $grid.data("gridOptions").calcRowAmount.call($grid, myrowdata);
                            $grid.jqGrid("setRowData", existRowId, myrowdata);
                        }else{
                            var myrowdata = {
                                    'commodity.sku' : item['sku'],//商品唯一性标识
                                    'commodity.id' : item.id,
                                    'commodity.barcode' : item.barcode,
                                    'price' : item.price,
                                    'measureUnit' : item.measureUnit,
                                    'commodity.display' : item.title,
                                    'storageLocation.id' : item['defaultStorageLocation.id'],
                                    'quantity' : 1,
                                    'discountRate' : 0,
                                    'deliveryAmount' : 0
                            };
                            $grid.data("gridOptions").calcRowAmount.call($grid, myrowdata);
                            existRowId = $grid.jqGrid("insertNewRowdata", myrowdata);
                        }
                        
                        // 整个Form相关金额字段更新
                        var $form = $grid.closest("form");
                        $form.data("formOptions").updateTotalAmount.call($form);
                        
                        // 计算并设置行项号
                        var idx = $grid.find("tr[id='" + existRowId + "'] >td.jqgrid-rownum").html().trim();
                        $grid.jqGrid('setRowData', existRowId, {
                            subVoucher : 100 + idx * 10
                        });
                    }
                    // 自动完成框的选取回调函数
                    var autocompleteSelectCommodity = function(item) {
                        
                        var ids = $grid.jqGrid('getDataIDs');// 返回当前grid里所有数据的id
                        
                        var existRowId = null;// 如果是已经选择过的商品，那么这是哪个商品的所在行行号
                        for(i=0; i<ids.length; i++){
                            var row = $grid.jqGrid('getRowData', ids[i]);//获取单行数据根据ID
                            if(item['sku'] == row['commodity.sku']){
                                // SKU一致即认为是同一商品
                                existRowId = ids[i];
                                break;
                            }
                        }
                        
                        if(existRowId){
                            var myrowdata = $grid.jqGrid('getRowData', existRowId);//获取单行数据根据ID
                            alert("所选商品已存在[ "+myrowdata.subVoucher+" | "+myrowdata['commodity.display']+" ]，请直接编辑数量字段。");
                            return;
                        }else{
                            var myrowdata = {
                                    'commodity.sku' : item['sku'],//商品唯一性标识
                                    'commodity.id' : item.id,
                                    'commodity.barcode' : item.barcode,
                                    'price' : item.price,
                                    'measureUnit' : item.measureUnit,
                                    'commodity.display' : item.title,
                                    'storageLocation.id' : item['defaultStorageLocation.id'],
                                    'quantity' : 1,
                                    'discountRate' : 0,
                                    'deliveryAmount' : 0
                            };
                            $grid.data("gridOptions").calcRowAmount.call($grid, myrowdata);
                            existRowId = $grid.jqGrid("setEditingRowdata", myrowdata);
                        }
                        
                        // 整个Form相关金额字段更新
                        var $form = $grid.closest("form");
                        $form.data("formOptions").updateTotalAmount.call($form);
                    }
                    $elem.dblclick(function() {
                        var rowdata = $grid.jqGrid("getEditingRowdata");
                        $(this).popupDialog({
                            url : WEB_ROOT + '/myt/md/commodity!forward?_to_=selectionMore',
                            title : '选取库存商品',
                            callback : function(item) {
                                selectCommodity(item);
                            }
                        })
                        // 多选模式双击弹出选取框之后，取消当前行编辑状态
                        $grid.closest("div.ui-jqgrid-view").find(".ui-pg-div span.ui-icon-cancel").click();
                    }).autocomplete({
                        autoFocus : true,
                        source : function(request, response) {
                            var data = Biz.queryCacheCommodityDatas(request.term);
                            return response(data);
                        },
                        minLength : 2,
                        select : function(event, ui) {
                            var item = ui.item;
                            this.value = item.display;

                            autocompleteSelectCommodity(item);
                            event.stopPropagation();
                            event.preventDefault();
                            return false;
                        },
                        change : function(event, ui) {
                            if (ui.item == null || ui.item == undefined) {
                                //$elem.val("");
                                $elem.focus();
                            }
                        }
                    }).focus(function() {
                        $elem.select();
                    });
                }
            },
            align : 'left'
        }, {
            label : '收货仓库',
            name : 'storageLocation.id',
            width : 150,
            editable : true,
            editrules : {
                required : true
            },
            stype : 'select',
            searchoptions : {
                value : Biz.getStockDatas()
            }
        }, {
            label : '批次号',
            name : 'batchNo',
            editable : true,
            width : 150
        }, {
            label : '单位',
            name : 'measureUnit',
            editable : true,
            width : 80
        }, {
            label : '数量',
            name : 'quantity',
            width : 80,
            formatter : 'number',
            editable : true,
            editrules : {
                required : true,
                number : true
            },
            editoptions : {
                dataInit : function(elem) {
                    var $grid = $(this);
                    var $elem = $(elem);
                    if ($elem.val() == "") {
                        $elem.val(1)
                    }
                    $elem.keyup(function() {
                        $grid.data("gridOptions").updateRowAmount.call($grid, $elem.closest("tr.jqgrow"));
                    });
                }
            },
            summaryType : 'sum',
            responsive : 'sm'
        }, {
            label : '单价',
            name : 'price',
            width : 80,
            formatter : 'currency',
            editable : true,
            editrules : {
                required : true,
                number : true
            },
            editoptions : {
                dataInit : function(elem) {
                    var $grid = $(this);
                    var $elem = $(elem);
                    $elem.keyup(function() {
                        $grid.data("gridOptions").updateRowAmount.call($grid, $elem.closest("tr.jqgrow"));
                    });
                }
            },
            responsive : 'sm'
        }, {
            label : '原价金额',
            name : 'originalAmount',
            width : 80,
            formatter : 'currency',
            editable : true,
            editoptions : {
                dataInit : function(elem) {
                    var $elem = $(elem);
                    $elem.attr("readonly", true);
                }
            },
            responsive : 'sm'
        }, {
            label : '折扣率(%)',
            name : 'discountRate',
            width : 80,
            formatter : 'currency',
            editable : true,
            editrules : {
                number : true
            },
            editoptions : {
                dataInit : function(elem) {
                    var $grid = $(this);
                    var $elem = $(elem);
                    $elem.keyup(function() {
                        $grid.data("gridOptions").updateRowAmount.call($grid, $elem.attr("name"));
                    });
                }
            },
            responsive : 'sm'
        }, {
            label : '折扣额',
            name : 'discountAmount',
            width : 80,
            editable : true,
            editoptions : {
                dataInit : function(elem) {
                    var $grid = $(this);
                    var $elem = $(elem);
                    $elem.keyup(function() {
                        $grid.data("gridOptions").updateRowAmount.call($grid, $elem.attr("name"));
                    });
                }
            },
            align : 'right',
            responsive : 'sm'
        }, {
            label : '折后金额',
            name : 'amount',
            width : 80,
            formatter : 'currency',
            editable : true,
            editoptions : {
                dataInit : function(elem) {
                    var $grid = $(this);
                    var $elem = $(elem);
                    $elem.keyup(function() {
                        $grid.data("gridOptions").updateRowAmount.call($grid, $elem.attr("name"));
                    });
                }
            },
            responsive : 'sm'
        }, {
            label : '分摊运费',
            name : 'deliveryAmount',
            width : 80,
            formatter : 'currency',
            editable : true,
            editoptions : {
                dataInit : function(elem) {
                    var $grid = $(this);
                    var $elem = $(elem);
                    if ($elem.val() == "") {
                        $elem.val(0)
                    }
                    var $form = $elem.closest("form");
                    $elem.keyup(function() {
                        $grid.data("gridOptions").updateRowAmount.call($grid, $elem.closest("tr.jqgrow"));
                    });
                }
            },
            responsive : 'sm'
        }, {
            label : '成本单价',
            name : 'costPrice',
            width : 80,
            formatter : 'currency',
            editable : true,
            editoptions : {
                dataInit : function(elem) {
                    var $elem = $(elem);
                    $elem.attr("readonly", true);
                }
            },
            responsive : 'sm'
        }, {
            label : '总成本',
            name : 'costAmount',
            width : 80,
            formatter : 'currency',
            editable : true,
            editoptions : {
                dataInit : function(elem) {
                    var $elem = $(elem);
                    $elem.attr("readonly", true);
                }
            },
            responsive : 'sm'
        } ],
        footerrow : true,
        beforeInlineSaveRow : function(rowid) {
            var $grid = $(this);
            $grid.data("gridOptions").updateRowAmount.call($grid);
        },
        afterInlineSaveRow : function(rowid) {
            var $grid = $(this);
            // 整个Form相关金额字段更新
            var $form = $grid.closest("form");
            $form.data("formOptions").updateTotalAmount.call($form);
        },
        afterInlineDeleteRow : function(rowid) {
            var $grid = $(this);
            // 整个Form相关金额字段更新
            var $form = $grid.closest("form");
            $form.data("formOptions").updateTotalAmount.call($form);
        },
        userDataOnFooter : true
    });
});